package com.sunk.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sunk.springcloud.entities.CommonResult;
import com.sunk.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Auther: Sunk
 * @Date: 2020/3/17 17:06
 * @Description:
 */
@RestController
@Slf4j
public class CircleBreakController {

    public static final String SERVICE_URL="http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback",fallback = "handleFallback") //负责java异常
    @SentinelResource(value="fallback",blockHandler = "blockHandler123")//负责sentinel控制台配置违规
    public CommonResult<Payment> fallback(@PathVariable Long id) throws IllegalAccessException {
        CommonResult<Payment> result= restTemplate.getForObject(SERVICE_URL+"/paymentSQL/"+id,CommonResult.class);

        if (id == 4){
            throw new IllegalAccessException("非常参数异常");
        }else if(result.getData()==null){
            throw new NullPointerException("该ID没有对应记录，空指针异常");
        }

        return result;
    }

    public CommonResult handleFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id,"null");
        return new CommonResult(444,e.getClass().getCanonicalName()+"\t 服务不可用",payment);
    }

    public CommonResult blockHandler123(BlockException e){
        return new CommonResult(444,"\t 服务不可用handleException");
    }

}
